package controllers

import (
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"news/cache"
	"news/models"
	"news/pkg"
	"time"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "数据不能为空",
		}
		c.ServeJSON()
		return
	}

	var user models.User
	user.Username = username
	user.Password = pkg.Md5(password)

	if err := user.FindUsername(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "系统错误",
		}
		c.ServeJSON()
		return
	}

	if user.ID > 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户已存在",
		}
		c.ServeJSON()
		return
	}

	if err := user.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "系统错误",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "数据不能为空",
		}
		c.ServeJSON()
		return
	}

	var user models.User
	user.Username = username
	user.Password = password

	key := fmt.Sprintf("password_error_%s", user.Username)
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()

	if err := user.FindUsername(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "系统错误",
		}
		c.ServeJSON()
		return
	}

	if user.ID < 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户不存在",
		}
		c.ServeJSON()
		return
	}

	if password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, key)
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码不正确",
		}
		c.ServeJSON()
		return
	}

	if count == 3 {
		cache.Rdb.Expire(cache.Ctx, key, time.Hour*2)
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "记录登录失败次数，达三次封禁两小时",
		}
		c.ServeJSON()
		return
	}

	cache.Rdb.Del(cache.Ctx, key) //清除错误次数
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "登入成功",
	}
	c.ServeJSON()

}
